package com.atguigu.gmall.activity.controller;

import com.atguigu.gmall.activity.config.CacheHelper;
import com.atguigu.gmall.activity.service.SeckillGoodsService;
import com.atguigu.gmall.common.constans.MqConst;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.model.activity.UserRecode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author 李旭
 * @date 2022/2/9
 * @Description:
 */
@RestController
@RequestMapping("/api/activity/seckill")
public class SeckillGoodsController {


    @Autowired
    private SeckillGoodsService seckillGoodsService;
    @Autowired
    private RabbitService rabbitService;
    @Autowired
    private RedisTemplate redisTemplate;
    //查询秒杀商品的集合
    @GetMapping("/findAll")
    public List<SeckillGoods> findAll(){

        return seckillGoodsService.findAll();
    }
    //查询一个秒杀商品
    @GetMapping("/findOne/{skuId}")
    public SeckillGoods findOne(@PathVariable Long skuId){
        return seckillGoodsService.findOne(skuId);
    }
    //获取抢购码
    @GetMapping("/auth/getSeckillSkuIdStr/{skuId}")
    public Result getSeckillSkuIdStr(@PathVariable Long skuId, HttpServletRequest request){
        //1:商品必须在活动范围之内
        //2:商品必须有货
        //3:商品必须审核通过的
        //以上全都符合 才会生成抢购码
        String userId = AuthContextHolder.getUserId(request);
        //UUID
        //加密方法 MD5  抢购码
        String skuIdStr = MD5.encrypt(userId + ":" + skuId);//用户ID:商品ID
        return Result.ok(skuIdStr);
    }
    //开始抢购
    @PostMapping("/auth/seckillOrder/{skuId}")
    public Result seckillOrder(@PathVariable Long skuId,String skuIdStr, HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
//        1、校验抢购码
        if(StringUtils.isEmpty(skuIdStr)){
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        }
        if(!skuIdStr.equals(MD5.encrypt(userId + ":" + skuId))){
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        };
//        2、校验状态位
        Object state = CacheHelper.get(skuId.toString());
        if(!"1".equals(state)){
            //无货
            return Result.build(null, ResultCodeEnum.SECKILL_FINISH);
        }
        UserRecode userRecode = new UserRecode();
        userRecode.setUserId(userId);//用户ID
        userRecode.setSkuId(skuId);//商品ID
//        3、发消息
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_SECKILL_USER,
                MqConst.ROUTING_SECKILL_USER,userRecode);
//        4、返回Result 200
        return Result.ok();
    }

    //查询秒杀结果
    @GetMapping("/auth/checkOrder/{skuId}")
    public Result checkOrder(@PathVariable Long skuId,HttpServletRequest request){
        //用户ID
        String userId = AuthContextHolder.getUserId(request);
//        查询秒杀结果
        //0:校验用户是否已买过   用户已经买过了  用户没有买过
        if(redisTemplate.hasKey(RedisConst.SECKILL_USER + userId + ":" + skuId)){
            //用户已经来过
//        1、查询用户是否有订单
            if(redisTemplate.hasKey(RedisConst.SECKILL_ORDERS_USERS + userId + ":" + skuId)){
                //有订单  SECKILL_ORDER_SUCCESS(218, "下单成功"),
                return Result.build(null,ResultCodeEnum.SECKILL_ORDER_SUCCESS);
            }
//        2、查询用户是否有资格
            if(redisTemplate.hasKey(RedisConst.SECKILL_ORDERS + userId + ":" + skuId)){
                //有资格 + 没有订单 == 抢购成功 去下单
                return Result.build(null,ResultCodeEnum.SECKILL_SUCCESS);
            }
            //抢购失败
            return Result.build(null,ResultCodeEnum.SECKILL_FAIL);
        }else{
            // 用户没有来过
            //校验状态位是否有货
            Object state = CacheHelper.get(skuId.toString());
            if("1".equals(state)){
                //排队中
                return Result.build(null,ResultCodeEnum.SECKILL_RUN);
            }else{
                //已售完
                return Result.build(null,ResultCodeEnum.SECKILL_FINISH);
            }
        }
    }
    /**
     *     // 使用Redis的Hash类型保存秒杀商品信息的
     *     public static final String SECKILL_GOODS = "seckill:goods";
     *
     *     //秒杀成功之后 保存秒杀资格的
     *     public static final String SECKILL_ORDERS = "seckill:orders:";
     *
     *     //用户提交秒杀商品的订单 保存在缓存中的Key值
     *     public static final String SECKILL_ORDERS_USERS = "seckill:orders:users:" + userId + ":" + skuId;
     *
     *    //使用Redis的List类型来保存秒杀商品的库存
     *     public static final String SECKILL_STOCK_PREFIX = "seckill:stock:";
     *     //校验用户是否已买
     *     public static final String SECKILL_USER = "seckill:user:" + userId + ":" + skuId;
     *
     *
     */
}
